import { Directive } from 'vue'
import { cacheUtils, LocalCacheKeys } from '@gyk/gyk-utils';

export const hasPermiFunction = (value: string[]): boolean => {
  const permissions = cacheUtils.localCache.getJSON(LocalCacheKeys.LOCAL_PERMISSIONS_KEY)
  const all_permission = "*:*:*";
  if (value && value instanceof Array && value.length > 0) {
    const permissionFlag = value

    const hasPermissions = permissions.some(permission => {
      return all_permission === permission || permissionFlag.includes(permission)
    })

    return !!hasPermissions
  } else {
    throw new Error(`请设置操作权限标签值`)
  }
}

const hasPermi: Directive<HTMLElement, string[]> = (el, binding) => {
  if (!hasPermiFunction(binding.value)) {
    el.parentNode && el.parentNode.removeChild(el)
  }
}

export default hasPermi